import React, { useEffect, useState } from 'react';
import { Skeleton, Divider } from 'antd';
import loadable from '@loadable/component';

import { getMerchList } from '@/service/api';
import styles from './ProductList.module.scss';

const FragmentList = loadable(() => import('@/pages/Fragment/List'), {fallback: <Skeleton style={{padding:6}} active />});

export default (props) => {
  const initState = () => ({
    items: [],
    loading: true,
    pageNo: 1,
    pageSize: 12,
    total: 0,
  });
  const [state, setState] = useState(initState);

  // 获取谷子列表
  const getList = async (options={}) => {
    const { pageNo, pageSize, } = state;
    const queryData = {pageNo, pageSize, ...options};

    setState(s => ({ ...s, loading: true }));
    try {
      const [res, err] = await getMerchList(queryData);
      if (err) return;
      const { records, current, total, size } = res?.data || {};
      const items = (1 === current ? [] : state.items).concat(records);
      setState(s => ({
        ...s,
        items,
        pageNo: current,
        pageSize: size,
        total,
      }));
    } finally {
      setState(s => ({ ...s, loading: false }));
    }
  };

  // 加载更多
  const onLoadMore = async () => {
    getList({ pageNo: state.pageNo + 1 });
  };

  // 首次加载
  useEffect(() => {
    getList();
  }, []);

  return (
    <FragmentList
      type="merch"
      dataSource={state.items}
      showMore={state.total && state.items?.length < state.total}
      onLoadMore={onLoadMore}
      loading={state.loading}
      grid={{
        gutter: [16, 16],
        xs: 2, sm: 2, md: 3, lg: 4, xl: 4, xxl: 4
      }}
    />
  );
};
